import React, { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'
import { getLibraryList } from './api/libraryService'
import Page from '../cc-news/Page'
import './css/library.less'

export default function LibraryList() {
    // 图书馆列表
    const [libraryList, setLibraryList] = useState<any>([])
    // 分页页码
    const [pageNum, setPageNum] = useState(1)
    // 分页列表
    const [pageSize, setPageSize] = useState(10)
    // 总页数
    const [pages, setPages] = useState(1)

    // 获取图书馆列表
    async function getLibraryListAll(params: any) {
        const res = await getLibraryList(params)
        console.log(res);
        setLibraryList(res.data.rows)
        setPages(Math.ceil(res.data.total / pageSize))
    }

    useEffect(() => {
        getLibraryListAll({
            pageNum,
            pageSize
        })
    }, [])

    // 更改页码
    function onChangePage(val: any) {
        getLibraryListAll({
            pageNum: val,
            pageSize
        })
        setPageNum(val)
    }

    // 跳转至图书馆的详情页
    const history = useHistory()
    function toDetail(item: any) {
        history.push(`/library/detail/${item.id}`)
    }

    return (
        <div className='library-list'>
            {libraryList.map((item: any) => {
                return <div key={item.id} className='library-item' onClick={() => { toDetail(item) }}>
                    <div>{item.name}</div>
                    <div>{item.address}</div>
                    <div className='time-state'>
                        <div>{item.businessHours}</div>
                        <div className={item.businessState === "1" ? 'state-in' : 'state-out'}>{item.businessState === '1' ? '正在营业' : '未营业'}</div>
                    </div>
                </div>
            })}
            <Page onChangePage={onChangePage} pagebtnall={pages} pagebtnnum={5} pagecur={pageNum}></Page>
        </div>
    )
}
